﻿
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Vml.Office;
using DocumentFormat.OpenXml.Vml;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using Outline = DocumentFormat.OpenXml.Wordprocessing.Outline;
using Run = DocumentFormat.OpenXml.Wordprocessing.Run;
using Text = DocumentFormat.OpenXml.Wordprocessing.Text;
using DataService.Office;
using Paragraph = DocumentFormat.OpenXml.Wordprocessing.Paragraph;
using DataService.Office.WordMain;



namespace TestOffice
{
    public static class TestWord
    {

        public static void AddWatermarkToWordDocument(string inputFilePath)
        {

            TestOutputWord(inputFilePath);

            // 打开现有的Word文档
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFilePath, true))
            {
                // 获取主文档部分
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;

                // 创建一个水印形状（例如文本框）
                TextBox textBox = new TextBox(
                    new DocumentFormat.OpenXml.Drawing.ShapeProperties(
                        new Transform2D(
                            new Offset() { X = 0, Y = 0 },
                            new Extents() { Cx = 914400L, Cy = 685800L }
                        ),
                        new PresetGeometry(
                            new AdjustValueList()
                        )
                    ),
                    new TextPath { String = new StringValue("测试水印"), On = new TrueFalseValue(true) }
                );

                // 设置水印的样式和属性（如字体、颜色、透明度等）
                textBox.Append(new StyleId() { Val = "WordArt" });
                //textBox.Append(new FillColor() { Val = "FFFFFF" }); // 白色背景
                textBox.Append(new Outline() { Val = OnOffValue.FromBoolean(false) }); // 无边框
                //textBox.Append(new InsetMode() { Val = false }); // 不内嵌
                 // textBox.Append(new LockedField() { Val = true }); // 锁定字段
                textBox.Append(new LockedField("呵呵呵呵呵")); // 锁定字段
               // textBox.Append(new WrappingStyle() { Val = WrappingStyleValues.Square }); // 方形包装
                //textBox.Append(new BehindDoc() { Val = true }); // 在文档后面
                textBox.Append(new Order() { Val = 1 }); // Z顺序
               // textBox.Append(new DrawingEffects() { Val = DrawingEffectsValues.Lighten }); // 变亮效果
                textBox.Append(new AlphaBiLevel() { Threshold = 0 }); // 透明度

                // 将水印添加到文档的主体部分
                mainPart.Document.Body.Append(textBox);

                // 保存文档
                mainPart.Document.Save();
            }
        }

        public static void TestOutputWord(string wordFullPath)
        {
            string str = @"测试文字啊手动阀手动阀手动阀";
            IXmlPackageBussiness packageBussiness = new XmlPackageBussiness();
            WordprocessingDocument wd = null;
            if (File.Exists(wordFullPath))
            {
                wd = packageBussiness.OpenDocumentPart(wordFullPath);
            }
            else
            {
                wd = packageBussiness.CreateDocumentPart(wordFullPath);
            }
            MainDocumentPart md = wd.MainDocumentPart;
            Body body = md.Document.Body;

            var currentElement = body.AppendChild<Paragraph>(new Paragraph());
            Run titleRun = currentElement.AppendChild(new Run());
            Text runtxt = new Text();
            runtxt.Text = str;

            titleRun.Append(runtxt);

            packageBussiness.AddHeader(md,"测试是不是页眉");
            packageBussiness.AddFooter(md, "测试页脚页脚页脚页脚");
            packageBussiness.AddWaterMark(md, "测试水印");
            packageBussiness.Save(md,new List<int>());


            wd.Dispose();
        }
        public static void SY_3(string wordFullPath)
        {
            string str = @"测试文字啊手动阀手动阀手动阀";
            IXmlPackageBussiness packageBussiness = new XmlPackageBussiness();
            WordprocessingDocument wd = null;
            if (File.Exists(wordFullPath))
            {
                wd = packageBussiness.OpenDocumentPart(wordFullPath);
            }
            else
            {
                wd = packageBussiness.CreateDocumentPart(wordFullPath);
            }
            MainDocumentPart md = wd.MainDocumentPart;
            Body body = md.Document.Body;

            var currentElement = body.AppendChild<Paragraph>(new Paragraph());
            Run titleRun = currentElement.AppendChild(new Run());
            Text runtxt = new Text();
            runtxt.Text = str;

            titleRun.Append(runtxt);

            packageBussiness.AddHeader(md, "页眉页眉页眉页眉页眉页眉");
            packageBussiness.AddWaterMark(md, "水印水印水印");
            packageBussiness.AddFooter(md, "页脚页脚页脚页脚页脚页脚页脚页脚");
            packageBussiness.Save(md, new List<int>());


            wd.Dispose();
        }

        public static void SY_2(string inputFilePath)
        {

            TestOutputWord(inputFilePath);

            // 打开现有的Word文档
            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(inputFilePath, true))
            {
                // 获取主文档部分
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;

               var shape= TestWord_3.CreateShape();
                DocumentFormat.OpenXml.Wordprocessing.Picture picture = new DocumentFormat.OpenXml.Wordprocessing.Picture();


                picture.Append(shape);
                var pageSize = new PageSize
                {
                    Width = 11906U,
                    Height = 16838U,
                    Orient = PageOrientationValues.Portrait
                };
                HeaderPart headerPart= XmlCall.XmlHeaderFooter.AddHeader(mainPart, "页眉页眉页眉");

                var secPrs = mainPart.Document.Descendants<SectionProperties>();
                if (secPrs.Count() == 0)
                {
                    /*设置 页眉，页脚和页面关系*/
                    string rId = mainPart.GetIdOfPart(headerPart);
                    SectionProperties sectPr = new SectionProperties(
                    new HeaderReference() { Id = rId, Type = HeaderFooterValues.Default }
                    );
                    sectPr.Append(pageSize);
                    mainPart.Document.Body.AppendChild<SectionProperties>(sectPr);
                }

                XmlCall.XmlHeaderFooter.AddFooter(mainPart, "页脚页脚页脚页脚");
                Paragraph paragraph = new Paragraph();
                Run run = new Run();
                run.Append(picture);
                paragraph.Append(run);


                headerPart.Header.Append(paragraph);


                // 保存文档
                mainPart.Document.Save();
            }
        }
        public static OpenXmlElement StringToOpenXmlElement(string text)
        {
            // 创建一个Run元素，它将包含文本内容
            Run run = new Run();
            // 创建一个Text元素，并将字符串设置为其内容
            Text textElement = new Text(text);
            // 将Text元素添加到Run元素中
            run.AppendChild(textElement);
            // 返回Run元素作为OpenXmlElement
            return run;
        }


        public static void SY_4(string inputFilePath)
        {
            TestOutputWord(inputFilePath);
            string watermarkText = "测试测试测试水印文字"; // 水印内容
         
            using (WordprocessingDocument doc = WordprocessingDocument.Open(inputFilePath, true))
            {
                MainDocumentPart mainPart = doc.MainDocumentPart;
                Body body = mainPart.Document.Body;

                // 创建水印段落
                Paragraph watermarkParagraph = new Paragraph(
                    new Run(
                        new Text(watermarkText),
                        new DocumentFormat.OpenXml.Wordprocessing.RunProperties(
                            new NoProof(),
                            new WebHidden()
                        )
                    ),
                    new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new SpacingBetweenLines() { LineRule = LineSpacingRuleValues.Auto },
                        new Indentation() { FirstLineChars = 0, Hanging = "0", Start = "0" }
                    )
                );

                // 将水印段落添加到文档的末尾
                body.AppendChild(watermarkParagraph);

                // 添加水印到每个页面
                foreach (SectionProperties section in mainPart.Document.Descendants<SectionProperties>())
                {
                    HeaderReference headerReference = new HeaderReference() { Type = HeaderFooterValues.Default };
                    headerReference.Id = "rId1";
                    section.InsertAt(headerReference, 0);

                    FooterReference headerFooterReference = new FooterReference();
                    headerFooterReference.Id = "rId1";
                    headerFooterReference.Type = HeaderFooterValues.Default;
                    section.InsertAt(headerFooterReference, 0);
                }

                // 保存更改后的文档
                mainPart.Document.Save();
            }

            Console.WriteLine("水印添加成功！");

        }

        public static void SY_5(string documentPath)
        {
            TestOutputWord(documentPath);

            string watermarkText = "DRAFT";

            using (WordprocessingDocument doc = WordprocessingDocument.Open(documentPath, true))
            {
               var headerParts= doc.MainDocumentPart.HeaderParts.ToList();
                // 遍历所有节  
                foreach (var section in doc.MainDocumentPart.Document.Body.Elements<SectionProperties>().Select((s, i) => new { Section = s, Index = i }))
                {
                    // 为每个节添加或修改页眉  
                    HeaderPart headerPart = null;
                    if (headerParts.Count > section.Index)
                    {
                        headerPart = headerParts[section.Index];
                    }
                    else
                    {
                        headerPart = doc.MainDocumentPart.AddNewPart<HeaderPart>();
                    }

                    // 创建页眉内容  
                    var header = new Header();

                    // 插入段落  
                    var paragraph = new Paragraph();
                    Run run = new Run();
                   DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties = new DocumentFormat.OpenXml.Wordprocessing.RunProperties();

                    // 设置水印文本的样式  
                    runProperties.Bold = new Bold();
                    runProperties.Italic = new Italic();
                    runProperties.FontSize = new FontSize { Val = "40" };
                    runProperties.Color = new Color { Val = "A0A0A0" }; // 灰色  
                    runProperties.VerticalTextAlignment = new VerticalTextAlignment { Val = VerticalPositionValues.Superscript };

                    // 插入文本  
                    Text text = new Text(watermarkText);

                    // 添加到Run  
                    run.Append(runProperties);
                    run.Append(text);

                    // 添加到Paragraph  
                    paragraph.Append(run);

                    // 添加到Header  
                    header.Append(paragraph);

                    // 将Header与HeaderPart关联  
                    headerPart.Header = header;

                    // 关联页眉到对应的节  
                    if (section.Section != null)
                    {
                        HeaderReference headerReference = new HeaderReference() { Type = HeaderFooterValues.Default, Id = headerPart.GetIdOfPart(doc.MainDocumentPart) };
                        section.Section.PrependChild<HeaderReference>(headerReference);
                    }
                }

                doc.MainDocumentPart.Document.Save();
            }


            Console.WriteLine("水印添加完成。");
        }
    }
}
